<?php
/** 
 * @file    login_handler.php - This file handles all login and logout calls
 *								it also checks if a user is logged in or not
 * @author  enflux
 * @version Aug-13-2010 
 * @todo    - Needs a better and safer login system
 *          
 */

// START FORM PROCESSING
if (isset($_POST['submit'])) { // Form has been submitted.
	$errors = array();
	// perform validations on the form data
	$required_fields = array('username', 'password');
	$errors = array_merge($errors, check_required_fields($required_fields, $_POST));
	$fields_with_lengths = array('username' => 30, 'password' => 30);
	$errors = array_merge($errors, check_max_field_lengths($fields_with_lengths, $_POST));
	$username = trim($_POST['username']);
	$password = trim($_POST['password']);
	$hashed_password = sha1($password);
	if ( empty($errors) ) {
		// Check database to see if username and the hashed password exist there.
		try {
			$query = "SELECT id, username FROM users WHERE username = '{$username}' AND hashed_password = '{$hashed_password}' LIMIT 1";
			$results = $sonic->query($query);
			$bypass = false;
			foreach($sonic->query($query) as $row) { 
				if ($row['username'] == $username) { //rowct doesn't work in sqlite :(
					$bypass = true; 
				}
				
			}
		}
		catch(PDOException $e) {
			echo $e->getMessage();
			die;
		}
		if ($results) {
			$rowct = $results->rowCount();

			//$test = $row;
			if (($rowct == 1) || ($bypass)) {
				// username/password authenticated
				// and only 1 match
				$found_user = $results->fetch(PDO::FETCH_ASSOC);
				$_SESSION['user_id'] = $found_user['id'];
				$_SESSION['username'] = $found_user['username'];
				header('Location: index.php');
			}
			if (DB_TYPE == 'sqlite') { $message = "Username/password mismatch"; }
		} else { 
			
			// username/password combo was not found in the database
			$message = "Username/password combination incorrect.<br />
				Please make sure your caps lock key is off and try again.";
		}
	} else { 
		if (count($errors) == 1) {
			$message = "There was 1 error in the form.";
		} else {
			$message = "There were " . count($errors) . " errors in the form.";
		}
	}
	
} 
else { // Form has not been submitted.
	if ($logout == true || isset($_GET['logout']) && $_GET['logout'] == 1) {
		$_SESSION = array();
		if(isset($_COOKIE[session_name()])) {
			setcookie(session_name(), '', time()-42000, '/');
		}
		session_destroy();

		$message = "You are now logged out.";
	} 
	elseif (isset($_SESSION['username'])) {
		$result = $sonic->query("SELECT * FROM users") or die("Jukebox not <a href='/setup.php'>setup</a>");
		$result = "SELECT * FROM users WHERE username = '".$_SESSION['username']."'";
		foreach($sonic->query($result) as $row) {
			if ($row['admin'] == 1) define('ADMIN','1');
			else define('ADMIN','0');
		}
	}
	$username = "";
	$password = "";
}
?>